package com.tree.thread;

import java.util.concurrent.Semaphore;

/**
 * @ClassName com.tree.thread
 * Description: <类功能描述>. <br>
 * <p>
 * 1. 三个线程轮流打印ABC
 *  a. 利用semaphore， 设置三个semaphore， permit分别为1，0，0，然后第一个执行完，阻塞当前，释放下一个，依次内推
 *  b. 利用标识， 比如说每个线程一个标识，当满足该标识， 则执行（可以利用synchronized或者lock来实现）
 * 2. 2个线程，轮流打印奇偶数
 *
 * </p>
 * @Author tree
 * @Date 2019-10-31 21:31
 * @Version 1.0
 */
public class SequencePrint {
    public static void main(String[] args) {
        SemaphorePrintABC semaphorePrintABC = new SemaphorePrintABC();
        new Thread(() -> semaphorePrintABC.printA()).start();

        new Thread(() -> semaphorePrintABC.printB()).start();

        new Thread(() -> semaphorePrintABC.printC()).start();
    }

    static class SemaphorePrintABC{
        private Semaphore A = new Semaphore(1);
        private Semaphore B = new Semaphore(0);
        private Semaphore C = new Semaphore(0);

        public void printA(){
            while (true) {
                try {
                    A.acquire();
                    print("A");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    B.release();
                }
            }
        }

        public void printB(){
            while (true) {
                try {
                    B.acquire();
                    print("B");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    C.release();
                }
            }
        }

        public void printC(){
            while (true) {
                try {
                    C.acquire();
                    print("C");
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    A.release();
                }
            }
        }

        public void print(String s){
            System.out.print(s);
        }
    }
}
